package com.jacen.etl.manager;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jodd.util.StringUtil;

public class ManageFilter implements Filter {
	
    private static final String USERNAME = "user";
    public static String PASSWORD;
    private Set<String> excludeUrls = new HashSet<String>();
    
    public void destroy() { 
    	
    }

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        
        String servletPath = request.getServletPath().toLowerCase();
        if (isContain(this.excludeUrls, servletPath)) {
            chain.doFilter(req, resp);
            return;
        }
        
        if (session.getAttribute(USERNAME) != null) {
            chain.doFilter(req, resp);
            return;
        }
      //  request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
        response.sendRedirect(request.getContextPath() + "/jsp/login.jsp");
    }

    public void init(FilterConfig config) throws ServletException {
    	PASSWORD = config.getInitParameter("appetl");
    	String urls = config.getInitParameter("excludeUrl");
        if(!StringUtil.isEmpty(urls)) {
        	String[] arrs = urls.split(",");
            this.excludeUrls.addAll(Arrays.asList(arrs));
        }
    }
    
    private boolean isContain(Set<String> urls, String servletPath){
    	for (String url : urls) if(url.equals(servletPath)) return true;
    	return false;
    }
}